package org.vs.handler;

import org.springframework.stereotype.Component;
import org.vs.annotation.ImageField;
import org.vs.config.StaticResourceConfig;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;

@Component
public class DataSettingHandler {
    @Resource
    private StaticResourceConfig staticResourceConfig;

    public void traverseObject(Object obj, boolean isAdvance) throws IllegalAccessException {
        for (Field field : obj.getClass().getDeclaredFields()) {
            try {
                field.setAccessible(true);
            } catch (Exception e) {
                break;
            }

            if (field.getType().equals(List.class)) {
                for (Object o : (List) field.get(obj)) {
                    traverseObject(o, isAdvance);
                }
            }

            if (field.getType().equals(Object.class)) {
                traverseObject(field.get(obj), isAdvance);
            }

            if (isAdvance) {
                beforeImageFieldHandler(field, obj);
            } else {
                returnImageFieldHandler(field, obj);
            }
        }
    }

    public void beforeImageFieldHandler(Field field, Object obj) throws IllegalAccessException {
        ImageField imageField = field.getAnnotation(ImageField.class);

        if (imageField == null) {
            return;
        }

        if (field.get(obj).toString().equals("")) {
            return;
        }

        field.set(obj, field.get(obj).toString().substring(staticResourceConfig.getUrlPrefix().length()));
    }

    public void returnImageFieldHandler(Field field, Object obj) throws IllegalAccessException {
        ImageField imageField = field.getAnnotation(ImageField.class);

        if (imageField == null) {
            return;
        }

        field.set(obj, staticResourceConfig.getUrlPrefix() + field.get(obj));
    }
}
